import { ref } from 'vue'

export function useVoiceRecognition() {
  const isRecording = ref(false)
  let recognitionInstance: any = null

  const startVoiceInput = (onResult: (transcript: string) => void) => {
    if (isRecording.value) {
      stopVoiceInput()
      return
    }
    
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
      // @ts-ignore
      const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
      recognitionInstance = new SpeechRecognition()
      
      recognitionInstance.lang = 'zh-CN'
      recognitionInstance.continuous = false
      recognitionInstance.interimResults = false
      
      recognitionInstance.onstart = () => {
        console.log('语音识别开始')
        isRecording.value = true
      }
      
      recognitionInstance.onresult = (event: any) => {
        const transcript = event.results[0][0].transcript
        onResult(transcript)
      }
      
      recognitionInstance.onerror = (event: any) => {
        console.error('语音识别错误:', event.error)
        isRecording.value = false
        recognitionInstance = null
      }
      
      recognitionInstance.onend = () => {
        console.log('语音识别结束')
        isRecording.value = false
        recognitionInstance = null
      }
      
      recognitionInstance.start()
    } else {
      console.log('浏览器不支持语音识别')
    }
  }

  const stopVoiceInput = () => {
    if (recognitionInstance) {
      try {
        recognitionInstance.stop()
        recognitionInstance = null
      } catch (error) {
        console.error('停止语音识别失败:', error)
      }
    }
    isRecording.value = false
  }

  return {
    isRecording,
    startVoiceInput,
    stopVoiceInput
  }
}